package controllers

import (
	"comment/models"
	"strconv"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

// UserController oprations for User
type UserController struct {
	BaseController
}

func (c *UserController) List() {
	var query = make(map[string]string)
	StatusList := map[int]string{1: "启用", 2: "禁用"}
	c.Data["PageTitle"] = "人员列表"
	pageNo, _ := c.GetInt("PageNo")
	if pageNo == 0 {
		pageNo = 1
	}
	size, _ := c.GetInt("SizePage")
	if size == 0 {
		size = 10
	}

	if v := c.GetString("account"); v != "" {
		query["account"] = v
	}

	if v := c.GetString("name"); v != "" {
		query["name"] = v
	}

	if v := c.GetString("status"); v != "" && v != "0" {
		query["status"] = v
	}

	if v := c.GetString("roles"); v != "" && v != "0" {
		query["roles"] = v
	}

	if v := c.GetString("job_number"); v != "" {
		query["job_number"] = v
	}

	if v := c.GetString("duty"); v != "" {
		query["duty"] = v
	}

	c.Data["size"] = size
	c.Data["Page"] = models.PageUser(pageNo, size, query)
	c.Data["RoleList"] = models.FindRoles()
	c.Data["StatusList"] = StatusList
	c.Data["Query"] = query
	Status, _ := strconv.Atoi(query["status"])
	Roles, _ := strconv.Atoi(query["roles"])
	c.Data["Status"] = Status
	c.Data["Roles"] = Roles
	c.Data["SizePage"] = size
	c.Data["safeAccount"] = beego.AppConfig.String("safeAccount")
	c.Layout = "layout/layout.html"
	c.TplName = "user/index.html"
}

func (c *UserController) Add() {
	beego.ReadFromRequest(&c.Controller)
	StatusList := map[int]string{1: "启用", 2: "禁用"}
	c.Data["StatusList"] = StatusList
	c.Data["PageTitle"] = "添加人员"
	c.Data["RoleList"] = models.FindRolesByStatus(1)
	c.Layout = "layout/layout.html"
	c.TplName = "user/add.html"
}

func (c *UserController) Save() {
	flash := beego.NewFlash()
	user := models.User{}
	if err := c.ParseForm(&user); err != nil {
		flash.Error("用户创建失败")
		flash.Store(&c.Controller)
		c.Redirect("/user/add", 302)
	} else {

		valid := validation.Validation{}
		valid.Required(user.Account, "用户名").Message("不能为空")
		valid.MinSize(user.Account, 5, "用户名").Message("长度必须大于等于2个字符")
		valid.MaxSize(user.Account, 20, "用户名").Message("长度必须小于等于10个字符")

		if v := models.FindUserByAccount(user.Account); v > 0 {
			valid.SetError("用户名", "已存在")
		}

		valid.Required(user.Password, "密码").Message("不能为空")
		valid.MinSize(user.Password, 5, "密码").Message("长度必须大于等于5个字符")
		valid.MaxSize(user.Password, 20, "密码").Message("长度必须小于等于10个字符")

		if v := c.GetString("RePassword"); v == "" {
			valid.SetError("确认密码", "不能为空")
		}

		if user.Password != c.GetString("RePassword") {
			valid.SetError("确认密码", "不一致")
		}

		valid.Required(user.Name, "人员姓名").Message("不能为空")
		valid.MinSize(user.Name, 2, "人员姓名").Message("长度必须大于等于2个字符")
		valid.MaxSize(user.Name, 10, "人员姓名").Message("长度必须小于等于10个字符")

		valid.Required(user.JobNumber, "工号").Message("不能为空")
		valid.Range(user.JobNumber, 1, 1000, "工号").Message("必须1000以内的纯整数数字")

		if v := models.FindUserByJobNumber(user.JobNumber, 0); v > 0 {
			valid.SetError("工号", "已存在")
		}

		valid.Required(user.Duty, "职务").Message("不能为空")
		valid.MinSize(user.Duty, 2, "职务").Message("长度必须大于等于2个字符")
		valid.MaxSize(user.Duty, 10, "职务").Message("长度必须小于等于10个字符")

		if valid.HasErrors() {
			for _, err := range valid.Errors {
				flash.Error(err.Key + " " + err.Message)
				flash.Store(&c.Controller)
				c.Redirect("/user/add/", 302)
				return
			}
		}

		_, err := models.SaveUser(&user)
		if err != nil {
			flash.Error("用户保存失败", err)
			flash.Store(&c.Controller)
			c.Redirect("/user/add", 302)
		} else {
			c.Redirect("/user/list", 302)
		}

	}

}

func (c *UserController) Edit() {
	beego.ReadFromRequest(&c.Controller)
	flash := beego.NewFlash()
	c.Data["PageTitle"] = "用户修改"
	id, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
	if id > 0 {
		StatusList := map[int]string{1: "启用", 2: "禁用"}
		c.Data["RoleList"] = models.FindRolesByStatus(1)
		c.Data["StatusList"] = StatusList
		c.Data["User"] = models.FindUserById(id)
		c.Layout = "layout/layout.html"
		c.TplName = "user/edit.html"
	} else {
		flash.Error("用户不存在")
		flash.Store(&c.Controller)
		c.Redirect("/user/edit/"+strconv.Itoa(id), 302)
	}
}

func (c *UserController) Update() {
	flash := beego.NewFlash()
	id, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
	if id > 0 {
		user := models.User{Id: id}
		if err := c.ParseForm(&user); err != nil {
			flash.Error("用户修改失败")
			flash.Store(&c.Controller)
			c.Redirect("/user/edit/"+strconv.Itoa(id), 302)
		} else {
			valid := validation.Validation{}
			valid.Required(user.Name, "人员姓名").Message("不能为空")
			valid.MinSize(user.Name, 2, "人员姓名").Message("长度必须大于等于2个字符")
			valid.MaxSize(user.Name, 10, "人员姓名").Message("长度必须小于等于10个字符")

			valid.Required(user.JobNumber, "工号").Message("不能为空")
			valid.Range(user.JobNumber, 1, 1000, "工号").Message("必须1000以内的纯整数数字")

			if v := models.FindUserByJobNumber(user.JobNumber, id); v > 0 {
				valid.SetError("工号", "已存在")
			}

			valid.Required(user.Duty, "职务").Message("不能为空")
			valid.MinSize(user.Duty, 2, "职务").Message("长度必须大于等于2个字符")
			valid.MaxSize(user.Duty, 10, "职务").Message("长度必须小于等于10个字符")

			if valid.HasErrors() {
				for _, err := range valid.Errors {
					flash.Error(err.Key + " " + err.Message)
					flash.Store(&c.Controller)
					c.Redirect("/user/edit/"+strconv.Itoa(id), 302)
					return
				}
			}

			models.UpdateUser(&user)
			c.Redirect("/user/list", 302)
		}
	} else {
		flash.Error("用户不存在")
		flash.Store(&c.Controller)
		c.Redirect("/role/edit/"+strconv.Itoa(id), 302)
	}
}

func (c *UserController) Password() {
	beego.ReadFromRequest(&c.Controller)
	flash := beego.NewFlash()
	c.Data["PageTitle"] = "密码修改"
	id, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
	if id > 0 {
		c.Data["User"] = models.FindUserById(id)
		c.Layout = "layout/layout.html"
		c.TplName = "user/password.html"
	} else {
		flash.Error("用户不存在")
		flash.Store(&c.Controller)
		c.Redirect("/user/password/"+strconv.Itoa(id), 302)
	}
}

func (c *UserController) UpdatePassword() {
	flash := beego.NewFlash()
	id, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
	if id > 0 {
		user := models.User{Id: id}
		if err := c.ParseForm(&user); err != nil {
			flash.Error("用户修改失败")
			flash.Store(&c.Controller)
			c.Redirect("/user/password/"+strconv.Itoa(id), 302)
		} else {
			valid := validation.Validation{}
			valid.Required(user.Password, "密码").Message("不能为空")
			valid.MinSize(user.Password, 5, "密码").Message("长度必须大于等于5个字符")
			valid.MaxSize(user.Password, 20, "密码").Message("长度必须小于等于10个字符")

			if v := c.GetString("RePassword"); v == "" {
				valid.SetError("确认密码", "不能为空")
			}

			if user.Password != c.GetString("RePassword") {
				valid.SetError("确认密码", "不一致")
			}

			if valid.HasErrors() {
				for _, err := range valid.Errors {
					flash.Error(err.Key + " " + err.Message)
					flash.Store(&c.Controller)
					c.Redirect("/user/password/"+strconv.Itoa(id), 302)
					return
				}
			}

			models.UpdatePassword(&user)
			c.Redirect("/user/list", 302)
		}
	} else {
		flash.Error("用户不存在")
		flash.Store(&c.Controller)
		c.Redirect("/role/password/"+strconv.Itoa(id), 302)
	}
}

func (c *UserController) Delete() {
	id, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
	if id > 0 {
		if err := models.DeleteUser(id, beego.AppConfig.String("safeAccount")); err == nil {
			c.Redirect("/user/list", 302)
		} else {
			c.Ctx.WriteString(err.Error())
		}
	} else {
		c.Ctx.WriteString("用户不存在")
	}

}
